<template>
  <div class="zw-date-range-picker">
    <el-date-picker style="width: 100%;" v-model="data.start" format="YYYY-MM-DD" value-format="YYYY-MM-DD 00:00:00"
      @change="onStartChanged"></el-date-picker>
    <div class="seperator">{{ props.seperator }}</div>
    <el-date-picker style="width: 100%;" v-model="data.end" format="YYYY-MM-DD" value-format="YYYY-MM-DD 00:00:00"
      @change="onEndChnaged"></el-date-picker>
  </div>
</template>
<script lang="ts" setup>
import DateUtil from '@/plugins/date';
import { ref } from 'vue';

const props = withDefaults(defineProps<{
  seperator: string
}>(), {
  seperator: " - "
})
const modelValue = defineModel<string[]>("modelValue");
const data = ref<{
  start: string,
  end: string
}>({
  start: modelValue.value && modelValue.value.length === 2 ? DateUtil.formatToTime(modelValue.value[0]) : "",
  end: modelValue.value && modelValue.value.length === 2 ? DateUtil.formatToTime(modelValue.value[1]) : "",
});
const onStartChanged = (value: string) => {
  if (value && data.value.end) {
    const start = DateUtil.parse(value);
    const end = DateUtil.parse(data.value.end);
    // 选择的时间合法
    data.value.start = start && end && start.getTime() <= end.getTime() ? value : "";
  }
  modelValue.value = [data.value.start || "", data.value.end || ""]
}
const onEndChnaged = (value: string) => {
  if (data.value.start && value) {
    const start = DateUtil.parse(data.value.start);
    const end = DateUtil.parse(value);
    // 选择的时间合法
    data.value.end = start && end && start.getTime() <= end.getTime() ? value : "";
  }
  modelValue.value = [data.value.start || "", data.value.end || ""];
}
</script>
<style lang="scss" scope>
.zw-date-range-picker {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;

  .seperator {
    margin: 0 8px;
  }
}
</style>
